package com.ubhave.powertrackernof1;

import java.util.Date;

import com.ubhave.powertrackernof1.R;

//import android.app.Activity;
import android.support.v4.app.FragmentActivity;
//import android.app.DialogFragment;
import android.support.v4.app.DialogFragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class DiariesMenuActivity extends FragmentActivity implements LoginDialogListener{
    
	String usr;
	String intervention;
	SharedPreferences settings;
	SharedPreferences.Editor editor;
	LifeGuideConnector lgc;
	
	PageSensorLogger psl;
	PageLogger pl;
	
	String activityPlan;
	String currenteatplan;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.diarymenu);
        
        //StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        //StrictMode.setThreadPolicy(policy);
        
        settings=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        editor = settings.edit();
        lgc=new LifeGuideConnector(settings);
    	
        usr = settings.getString("LifeGuideUser", "");
		intervention = settings.getString("LifeGuideInterventionId", "");
        
		activityPlan = settings.getString("PAplan", "");
		currenteatplan = settings.getString("currenteatplan", "");
		
		setPlanButton();
		
		if(settings.getBoolean("SensorsOn", false))    		
			psl = new PageSensorLogger(this);
		pl = new PageLogger(this);
				
		class AsyncLogAndRetrieve extends AsyncTask{

			@Override
			protected Object doInBackground(Object... params) {
				//Usage Logging
				/*editor.putString("usageLog", settings.getString("usageLog", "")+params[0].getClass().getSimpleName()+" "+new Date()+", ");
        		editor.commit();
        		if(!usr.equals("")&&!intervention.equals(""))
        			lgc.postVar(intervention, usr, "user", "appUsageLog", settings.getString("usageLog", ""),settings.getString("authkey",""));
        		else
        			Log.i("POWeR Tracker: ", "Log fail usr: "+usr+" int: "+intervention);*/
				try{
					pl.makeLog();
        
        			//Sensor Logging
        			if(settings.getBoolean("SensorsOn", false)){
    					psl.makeLog();
        			}
        		
        			//Load eat/activity plan
        			String planValue = lgc.getVar(intervention, usr, "user", "PAplan",settings.getString("authkey",""));
        		
        			if(planValue!=null){
        				editor.putString("PAplan", planValue);
        				editor.commit();
        				activityPlan =planValue;
        			}
        		
        			String eatPlanValue = lgc.getVar(intervention, usr, "user", "currenteatplan",settings.getString("authkey",""));
        		
        			if(eatPlanValue!=null){
        				editor.putString("currenteatplan", eatPlanValue);
        				editor.commit();
        				currenteatplan =eatPlanValue;
        			}
        		
        			Log.i("POWeR Tracker Special: ","Logged for Diary");
				} catch (PowerTrackerInvalidAuthKeyException e) {
					invalidKey();
				}
				
        		return null;
			}
			
			protected void onPostExecute(Object result) {
				setPlanButton();
		    }
		};
        new AsyncLogAndRetrieve().execute(this);

    }
    
    @Override
    protected void onPause() {
        super.onPause();
        if(psl!=null)
        	psl.stopLocationSensing();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        if(psl!=null)
        	psl.resumeLocationSensing();
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        	
    	switch (item.getItemId()) {
            case android.R.id.home:
                // app icon in action bar clicked; go home
                goHome();
                return true;
            case R.id.home:
                // app icon in options clicked; go home
            	goHome();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.o_menu, menu);
        return true;
    }
    
    public void goHome(){
    	Intent intent = new Intent(this, PowerTrackerActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
    
    public void goActivityDiary(View v){
    	
    	Intent myIntent = new Intent().setClass(this, DiaryActivity.class);
    	myIntent.putExtra("title", "Activity Diary");
    	myIntent.putExtra("name", "activity");
        startActivityForResult(myIntent, 0);
    	
    }

    public void goFoodDiary(View v){
	
    	Intent myIntent = new Intent().setClass(this, DiaryActivity.class);
    	myIntent.putExtra("title", "Food Diary");
    	myIntent.putExtra("name", "food");
    	startActivityForResult(myIntent, 0);
	
    }
    
    public void goDiaryHelp(View v){
    	
    	currenteatplan=settings.getString("currenteatplan", "");
    	
    	Intent myIntent = new Intent().setClass(this, StaticContentActivity.class);
    	if(currenteatplan.equals("cal"))
    		myIntent.putExtra("page", "diaryhelp_cal");
    	else
    		myIntent.putExtra("page", "diaryhelp_carb");
        startActivityForResult(myIntent, 0);
    	
    }
    
    public void setPlanButton(){
    	if(activityPlan!=null){
        	if(activityPlan.equals("walk")){
        		Button ab = (Button)findViewById(R.id.ActivityDiaryButton);
        		ab.setText("Walking Diary");
        	}
        	else{
        		Button ab = (Button)findViewById(R.id.ActivityDiaryButton);
        		ab.setText("Activity Diary");
        	}
        }    	
    }
    
    public void invalidKey(){
		DialogFragment dialog = new LoginDialog();
		Bundle errorBundle = new Bundle();
	    errorBundle.putString("error", "Your Authentication Key is invalid, expired, or is missing. Please Log In.");
	    dialog.setArguments(errorBundle);
	    //dialog.show(this.getFragmentManager(), "LoginDialog");
	    dialog.show(this.getSupportFragmentManager(), "LoginDialog");
	}
    
  	@Override
	public void onLoginDialogPositiveClick() {
		// TODO Auto-generated method stub
  		Log.i("POWeR Tracker Special: ","Clicked OK");
  		finish();
  		startActivity(getIntent());
	}


	@Override
	public void onLoginDialogNegativeClick() {
		// TODO Auto-generated method stub
		Log.i("POWeR Tracker Special: ","Clicked Cancel");
		goHome();
	}
    
}